﻿Public Class frmMain
    Private ExpireDate As Date = #12/31/2013#
    Private WithEvents puConfigFile As New ConfigFile
    Private FormLoading As Boolean = True
    Private CurrentOpenedFile As New OpenedFile
    Private WithEvents MyPlatformPlanValue As L3DPlatformPlan

    Enum MessageType
        Saving = 1
        Saved = 2
        Loading = 3
        Loaded = 4
        Exporting = 5
        Exported = 6
    End Enum
    Private Structure OpenedFile
        Dim Name As String
        Dim Type As FileType
        Dim LastModificationSaved As Boolean
        Enum FileType
            XMLFile = 1
            XLSFile = 2
        End Enum
    End Structure
    Private Property MyPlatformPlan As L3DObjectsLibrary.L3DPlatformPlan
        Get
            If Splitter.Panel2.Controls.Count > 0 Then
                Return Splitter.Panel2.Controls(0)
            Else
                Return Nothing
            End If
        End Get
        Set(ByVal value As L3DObjectsLibrary.L3DPlatformPlan)
            Splitter.Panel2.Controls.Clear()
            With value
                .Parent = Splitter.Panel2
                .Dock = System.Windows.Forms.DockStyle.Fill
            End With
        End Set
    End Property

    Private Sub cmdKmUpdate_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdKmUpate.Click, mnuKmUpdate.Click
        Dim UpdateForm As New frmMileageLoad
        With UpdateForm
            .Project = MyPlatformPlan.ActiveProject.Project
            .Owner = Me
            .ShowDialog()
        End With
    End Sub
    Private Sub cmdEsporta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEsporta.Click, mnuFileEsporta.Click
        Dim pModello As String = MyPlatformPlan.PresentationModel
        Dim pOwner As String = MyPlatformPlan.PresentationOwner
        Dim ElencoFile As String = ""
        If chkPPT.Checked = False And chkXLS.Checked = False Then
            MsgBox("Non è selezionata nessuna opzione di esportazione.")
            Exit Sub
        End If
        Dim pSaveFile As New System.Windows.Forms.SaveFileDialog
        With pSaveFile
            .InitialDirectory = puConfigFile.LastExportDir
            .FileName = Format(Now, "yyyyMMdd-hhmmss") & " Stato validazione " & pModello & " di " & pOwner
            .Filter = "File di Microsoft PowerPoint (*.ppt)|*.ppt"
            If .ShowDialog = DialogResult.OK Then
                If chkPPT.Checked = True Then
                    Dim PPTTranslator As New L3DTranslators.PowerpointOperations.PowerPointTranslator
                    AddHandler PPTTranslator.ProjectExported, AddressOf Translator_ProjectConverted
                    StatusBarMessaging(MessageType.Exporting)
                    PPTTranslator.BuildPowerPointPresentation(MyPlatformPlan, .FileName)
                    StatusBarMessaging(MessageType.Exported)
                    ElencoFile = ElencoFile & .FileName & Chr(13)
                End If
                If chkXLS.Checked = True Then
                    Dim NomeFile As String = .FileName & ".xls"
                    Dim XLSTranslator As New L3DTranslators.ExcelOperations.XLSTranslator
                    XLSTranslator.BuildResumeTable(MyPlatformPlan, NomeFile)
                    ElencoFile = ElencoFile & NomeFile
                End If
                frmDialogresult.lblText.Text = "Esportazione completata con successo nei seguenti file:" & Chr(13) & ElencoFile
                frmDialogresult.ShowDialog()
                puConfigFile.LastExportDir = .FileName
            End If
        End With
        AggiornaRecentFileList()
    End Sub
    Private Sub cmdOpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOpenFile.Click, mnuFileApri.Click
        Dim pOpenFile As New System.Windows.Forms.OpenFileDialog
        If AskForSaving() = False Then
            Exit Sub
        End If
        With pOpenFile
            .InitialDirectory = puConfigFile.LastOpenDir
            .Filter = "File di progetto di L3D (*.xl3d)|*.xl3d|File di dati i L3D in formato Excel (*.xls)|*.xls"
            If .ShowDialog = DialogResult.OK Then
                OpenFile(.FileName, .FilterIndex)
            End If
        End With
    End Sub
    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If DateTime.Compare(Now, ExpireDate) > 0 Then
            MsgBox("La licenza per l'uso di questo software non è più valida. Contattare il produttore per ottenere una nuova licenza o verificare la presenza di una versione aggiornata.")
            Me.Close()
        End If
        Dim FileCheck As New System.IO.FileInfo(puConfigFile.FilePath)
        If FileCheck.Exists = False Then
            puConfigFile.Create()
        End If
        numRecentFiles.Value = puConfigFile.RecentFileNumber
        AggiornaRecentFileList()
        Dim CommandLineArgs() As String = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData
        If CommandLineArgs IsNot Nothing Then
            Dim CommandLine As Uri = New Uri(CommandLineArgs(0))
            Dim FileName As String = CommandLine.LocalPath
            FileCheck = New System.IO.FileInfo(FileName)
            If FileCheck.Exists = True Then
                OpenFile(FileName, OpenedFile.FileType.XMLFile)
            End If
        Else
            MyPlatformPlan = New L3DObjectsLibrary.L3DPlatformPlan
        End If
        Dim MailSender As New System.Net.Mail.SmtpClient
        Me.Text = My.Application.Info.ProductName & String.Format(" Versione {0}.{1}.{2}", My.Application.Info.Version.Major, My.Application.Info.Version.Minor, My.Application.Info.Version.Build)
        FormLoading = False
    End Sub
    Private Sub lstRecentFiles_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstRecentFiles.DoubleClick
        If sender Is lstRecentFiles And lstRecentFiles.SelectedItem <> "" Then
            If AskForSaving() = False Then
                Exit Sub
            End If
            Dim FileSystem As New System.IO.FileInfo(lstRecentFiles.SelectedItem)
            If FileSystem.Exists = False Then
                MsgBox("Il file selezionato non esiste o è stato rimosso.")
                puConfigFile.RemoveRecenFile(lstRecentFiles.SelectedItem)
                Exit Sub
            End If
            With lstRecentFiles
                If .SelectedIndex >= 0 Then
                    If LCase(Strings.Right(lstRecentFiles.SelectedItem, 3)) = "xls" Or LCase(Strings.Right(lstRecentFiles.SelectedItem, 4)) = "xlsx" Then
                        OpenFile(lstRecentFiles.SelectedItem, OpenedFile.FileType.XLSFile)
                    ElseIf LCase(Strings.Right(lstRecentFiles.SelectedItem, 4)) = "xl3d" Then
                        OpenFile(lstRecentFiles.SelectedItem, OpenedFile.FileType.XMLFile)
                    End If
                End If
                AggiornaRecentFileList()
            End With
        End If
    End Sub
    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSaveAs.Click, cmdSave.Click, mnuFileSaveAs.Click, mnuFileSave.Click
        If sender Is cmdSaveAs Or sender Is mnuFileSaveAs Or CurrentOpenedFile.Name = "" Then
            Dim SaveDialog As New System.Windows.Forms.SaveFileDialog
            With SaveDialog
                .InitialDirectory = puConfigFile.LastSaveDir
                .FileName = "Pianificazione di L3D"
                .Filter = "File di L3D (*.xl3d)|*.xl3d"
                If .ShowDialog = DialogResult.OK Then
                    StatusBarMessaging(MessageType.Saving)
                    Dim Translator As New L3DTranslators.XMLOperations.XMLTranslator
                    AddHandler Translator.ProjectConvertedToXProject, AddressOf Translator_ProjectConverted
                    Dim XPlan As XElement = Translator.L3dPlatformPlanToXML(MyPlatformPlan)
                    XPlan.Save(.FileName)
                    StatusBarMessaging(MessageType.Saved)
                    puConfigFile.LastSaveDir = .FileName
                    puConfigFile.AddRecentFile(.FileName)
                    CurrentOpenedFile.Name = .FileName
                    CurrentOpenedFile.Type = OpenedFile.FileType.XMLFile
                End If
            End With
        ElseIf CurrentOpenedFile.Name <> "" Then
            StatusBarMessaging(MessageType.Saving)
            Dim Translator As New L3DTranslators.XMLOperations.XMLTranslator
            AddHandler Translator.ProjectConvertedToXProject, AddressOf Translator_ProjectConverted
            Dim XPlan As XElement = Translator.L3dPlatformPlanToXML(MyPlatformPlan)
            XPlan.Save(CurrentOpenedFile.Name)
            StatusBarMessaging(MessageType.Saved)
        End If
        AggiornaRecentFileList()
        MyPlatformPlan.LastModificationSaved = True
    End Sub
    Private Sub cmdNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdNew.Click, mnuFileNuovo.Click
        If AskForSaving() = False Then
            Exit Sub
        End If
        MyPlatformPlan = New L3DObjectsLibrary.L3DPlatformPlan
    End Sub
    Private Sub numRecentFiles_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles numRecentFiles.ValueChanged
        If sender Is numRecentFiles And FormLoading = False Then
            puConfigFile.RecentFileNumber = numRecentFiles.Value
            AggiornaRecentFileList()
        End If
    End Sub
    Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click, cmdAbout.Click
        frmAbout.Show()
    End Sub
    Private Sub Translator_ProjectConverted()
        progStatusbar.Increment(1)
    End Sub
    Private Sub Plan_QueryChange(ByVal sender As Object, ByVal e As QueryChangeEventArgs) Handles MyPlatformPlanValue.QueryChange
        CurrentOpenedFile.LastModificationSaved = False
    End Sub

    Private Sub AggiornaRecentFileList()
        lstRecentFiles.Items.Clear()
        For Each pFile As String In puConfigFile.RecentFilesList
            lstRecentFiles.Items.Add(pFile)
        Next
    End Sub
    Private Sub StatusBarMessaging(ByVal Status As MessageType)
        With lblStatusBar
            .Visible = True
        End With
        Select Case Status
            Case MessageType.Saving
                With lblStatusBar
                    .Text = "Salvataggio"
                    .Visible = True
                End With
                With progStatusbar
                    .Value = 0
                    .Maximum = MyPlatformPlan.Projects.Count
                    .Visible = True
                End With
            Case MessageType.Saved
                progStatusbar.Visible = False
                lblStatusBar.Text = "Documento salvato"
                Dim MyTimer As New Timer
                MyTimer.Interval = 5000
                AddHandler MyTimer.Tick, AddressOf ResetStatusBar
                MyTimer.Start()
            Case MessageType.Loading
            Case MessageType.Loaded
            Case MessageType.Exporting
                With lblStatusBar
                    .Text = "Esportazione"
                    .Visible = True
                End With
                With progStatusbar
                    .Value = 0
                    .Maximum = MyPlatformPlan.Projects.Count
                    .Visible = True
                End With
            Case MessageType.Exported
                progStatusbar.Visible = False
                lblStatusBar.Text = "Esportazione completata"
                Dim MyTimer As New Timer
                MyTimer.Interval = 5000
                AddHandler MyTimer.Tick, AddressOf ResetStatusBar
                MyTimer.Start()
        End Select
    End Sub
    Private Sub ResetStatusBar(ByVal sender As Object, ByVal e As System.EventArgs)
        lblStatusBar.Visible = False
        progStatusbar.Visible = False
        If sender.GetType = GetType(Timer) Then
            sender = Nothing
        End If
    End Sub
    Private Function AskForSaving() As Boolean
        Dim Result As Boolean = False
        If MyPlatformPlan IsNot Nothing And MyPlatformPlan.LastModificationSaved = False Then
            Dim Answer = MsgBox("Salvare le ultime modifiche?", MsgBoxStyle.YesNoCancel, "Salva modifiche")
            If Answer = vbOK Then
                cmdSave.PerformClick()
                Result = True
            ElseIf Answer = vbCancel Then
                Result = False
            Else
                Result = True
            End If
        Else
            Result = True
        End If
        Return Result
    End Function
    Private Sub OpenFile(ByVal FileName As String, ByVal FileType As Integer)
        Splitter.Panel2.Controls.Clear()
        If FileType = OpenedFile.FileType.XLSFile Then
            Dim Translator As New L3DTranslators.ExcelOperations.XLSTranslator
            If L3DTranslators.ExcelOperations.XLSFunctions.FileFormatVerification(FileName, "", "") = False Then Exit Sub
            If L3DTranslators.ExcelOperations.XLSFunctions.FileSyntaxVerification(FileName) = False Then Exit Sub
            MyPlatformPlan = Translator.XLSFileImport(FileName)
        ElseIf FileType = OpenedFile.FileType.XMLFile Then
            Dim XFile As XElement
            XFile = XElement.Load(FileName)
            Dim Translator As New L3DTranslators.XMLOperations.XMLTranslator
            AddHandler Translator.ProjectConvertedToXProject, AddressOf Translator_ProjectConverted
            MyPlatformPlan = Translator.XMLStructureToL3DPlatformPlan(XFile)
            CurrentOpenedFile.Name = FileName
            CurrentOpenedFile.Type = OpenedFile.FileType.XMLFile
        End If
        puConfigFile.LastOpenDir = FileName
        puConfigFile.AddRecentFile(FileName)
    End Sub
    Private Sub puConfigFile_Fileupdated(ByVal sender As Object, ByVal PropertyUpdated As String) Handles puConfigFile.FileUpdated
        If PropertyUpdated = ConfigFile.ConfigFileProperties.RecentFilesList Then
            AggiornaRecentFileList()
        End If
    End Sub
End Class
